<template>
  <div class="multi-level-checkbox">
    <!-- 搜索区域 -->
    <div class="search-section">
      <label class="search-label">角色权限:</label>
      <div class="search-input-group">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入菜单名称"
          class="search-input"
          @input="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </div>

    <!-- 权限列表区域 -->
    <div class="permissions-container">
      <div class="permissions-list" ref="permissionsList">
        <!-- 全选 -->
        <div class="permission-item select-all">
          <el-checkbox
            v-model="selectAll"
            @change="handleSelectAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
        </div>

        <!-- 权限项 -->
        <div
          v-for="category in filteredPermissions"
          :key="category.id"
          class="permission-category"
          :class="{ 'highlighted': category.highlighted }"
        >
          <!-- 主分类 -->
          <div class="permission-item main-category">
            <el-checkbox
              v-model="category.checked"
              @change="handleCategoryChange(category)"
            >
              {{ category.name }}
            </el-checkbox>
          </div>

          <!-- 子分类 -->
          <div
            v-for="subCategory in category.children"
            :key="subCategory.id"
            class="sub-category"
            :class="{ 'highlighted': subCategory.highlighted }"
          >
            <div class="permission-item sub-category-item">
              <el-checkbox
                v-model="subCategory.checked"
                @change="handleSubCategoryChange(category, subCategory)"
              >
                {{ subCategory.name }}
              </el-checkbox>
            </div>

            <!-- 操作权限 -->
            <div class="actions-container">
              <div
                v-for="action in subCategory.actions"
                :key="action.id"
                class="action-item"
              >
                <el-checkbox
                  v-model="action.checked"
                  @change="handleActionChange(category, subCategory, action)"
                >
                  {{ action.name }}
                </el-checkbox>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

// Props
const props = defineProps({
  permissions: {
    type: Array,
    default: () => []
  },
  modelValue: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change'])

// 响应式数据
const searchKeyword = ref('')
const permissionsList = ref(null)

// 计算属性
const filteredPermissions = computed(() => {
  if (!searchKeyword.value) {
    return props.permissions
  }
  
  return props.permissions.filter(category => {
    // 检查主分类是否匹配
    const categoryMatch = category.name.includes(searchKeyword.value)
    
    // 检查子分类是否匹配
    const subCategoryMatch = category.children?.some(subCategory => 
      subCategory.name.includes(searchKeyword.value) ||
      subCategory.actions?.some(action => action.name.includes(searchKeyword.value))
    )
    
    return categoryMatch || subCategoryMatch
  }).map(category => {
    // 高亮匹配的项
    const highlightedCategory = { ...category }
    
    if (category.children) {
      highlightedCategory.children = category.children.map(subCategory => {
        const highlightedSubCategory = { ...subCategory }
        
        if (subCategory.actions) {
          highlightedSubCategory.actions = subCategory.actions.map(action => ({
            ...action,
            highlighted: action.name.includes(searchKeyword.value)
          }))
        }
        
        highlightedSubCategory.highlighted = subCategory.name.includes(searchKeyword.value) ||
          highlightedSubCategory.actions?.some(action => action.highlighted)
        
        return highlightedSubCategory
      })
    }
    
    highlightedCategory.highlighted = category.name.includes(searchKeyword.value) ||
      highlightedCategory.children?.some(subCategory => subCategory.highlighted)
    
    return highlightedCategory
  })
})

// 全选状态
const selectAll = computed({
  get() {
    const allItems = getAllItems()
    return allItems.length > 0 && allItems.every(item => item.checked)
  },
  set(value) {
    // 这个setter不会被直接调用，通过handleSelectAll处理
  }
})

// 半选状态
const isIndeterminate = computed(() => {
  const allItems = getAllItems()
  const checkedCount = allItems.filter(item => item.checked).length
  return checkedCount > 0 && checkedCount < allItems.length
})

// 获取所有可选择的项目
const getAllItems = () => {
  const items = []
  props.permissions.forEach(category => {
    items.push(category)
    if (category.children) {
      category.children.forEach(subCategory => {
        items.push(subCategory)
      })
    }
  })
  return items
}

// 事件处理
const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const handleSelectAll = (checked) => {
  const allItems = getAllItems()
  allItems.forEach(item => {
    item.checked = checked
  })
  emitChange()
}

const handleCategoryChange = (category) => {
  // 主分类变化时，影响所有子项
  if (category.children) {
    category.children.forEach(subCategory => {
      subCategory.checked = category.checked
      if (subCategory.actions) {
        subCategory.actions.forEach(action => {
          action.checked = category.checked
        })
      }
    })
  }
  emitChange()
}

const handleSubCategoryChange = (category, subCategory) => {
  // 子分类变化时，影响其下的所有操作
  if (subCategory.actions) {
    subCategory.actions.forEach(action => {
      action.checked = subCategory.checked
    })
  }
  
  // 检查是否需要更新主分类状态
  updateCategoryState(category)
  emitChange()
}

const handleActionChange = (category, subCategory, action) => {
  // 操作变化时，检查是否需要更新上级状态
  updateSubCategoryState(subCategory)
  updateCategoryState(category)
  emitChange()
}

// 更新子分类状态
const updateSubCategoryState = (subCategory) => {
  if (subCategory.actions) {
    const allChecked = subCategory.actions.every(action => action.checked)
    const someChecked = subCategory.actions.some(action => action.checked)
    
    if (allChecked) {
      subCategory.checked = true
    } else if (someChecked) {
      subCategory.checked = false // 半选状态，这里可以根据需要调整
    } else {
      subCategory.checked = false
    }
  }
}

// 更新主分类状态
const updateCategoryState = (category) => {
  if (category.children) {
    const allChecked = category.children.every(subCategory => subCategory.checked)
    const someChecked = category.children.some(subCategory => subCategory.checked)
    
    if (allChecked) {
      category.checked = true
    } else if (someChecked) {
      category.checked = false // 半选状态
    } else {
      category.checked = false
    }
  }
}

// 发出变化事件
const emitChange = () => {
  const selectedItems = getAllItems().filter(item => item.checked)
  emit('update:modelValue', selectedItems)
  emit('change', selectedItems)
}

// 监听props变化
watch(() => props.permissions, (newPermissions) => {
  // 当权限数据变化时，可以在这里处理
}, { deep: true })
</script>

<style scoped>
.multi-level-checkbox {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.search-label {
  font-weight: bold;
  color: #333;
  white-space: nowrap;
}

.search-input-group {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.search-input {
  max-width: 300px;
}

.permissions-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
}

.permissions-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;
}

.permission-item {
  padding: 8px 12px;
  border-radius: 4px;
  margin-bottom: 2px;
}

.permission-item:hover {
  background-color: #f5f7fa;
}

.permission-category {
  margin-bottom: 8px;
}

.permission-category.highlighted {
  background-color: #fff2e8;
  border: 2px solid #ff6b35;
  border-radius: 4px;
  padding: 8px;
}

.main-category {
  font-weight: bold;
  color: #333;
  background-color: #f8f9fa;
  border-left: 3px solid #409eff;
}

.sub-category {
  margin-left: 20px;
  margin-top: 4px;
}

.sub-category.highlighted {
  background-color: #fff2e8;
  border: 1px solid #ff6b35;
  border-radius: 4px;
  padding: 4px;
}

.sub-category-item {
  font-weight: 500;
  color: #666;
}

.actions-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-left: 20px;
  margin-top: 4px;
}

.action-item {
  padding: 4px 8px;
  background-color: #f0f2f5;
  border-radius: 4px;
  font-size: 14px;
}

.action-item:hover {
  background-color: #e6f7ff;
}

.select-all {
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 10px;
  padding-bottom: 10px;
  font-weight: bold;
  color: #333;
}

/* 滚动条样式 */
.permissions-list::-webkit-scrollbar {
  width: 6px;
}

.permissions-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.permissions-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.permissions-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
